<?php

namespace App\Http\Controllers\Admin;

use App\Classes\UploadImg;
use App\Http\Controllers\AdminController;
use App\Jobs\SetAdminLog;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;

class MeController extends AdminController
{
    /**
     * 验证条件数组
     * @var array
     */
    protected $verifyFactor = [
        'password'      => 'required|confirmed|min:6'
    ];

    /**
     * 我的面板
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function getIndex()
    {
        return view('admin.me');
    }

    /**
     * 修改资料
     * @param Request $request
     * @return $this
     */
    public function postEdit(Request $request)
    {
        //验证
        $verifyMsg = $this->verification(
            $request->input('password') ? $request->input() : $request->except('password'),
            $request->has('email') ? ['email' => 'email|max:255|unique:users,email,'.$this->user->id] : [],
            $request->has('realName') ? ['realName' => 'max:255'] : [],
            $request->has('phone') ? ['phone' => 'max:255'] : []
        );
        if ($verifyMsg)
        {
            return redirect()->back()->withInput()->withErrors($verifyMsg);
        }
        //整理数据
        if ($request->input('password'))
            $request->merge(['password' => bcrypt($request->input('password'))]);

        //修改前的值
        $origin = User::find($this->user->id)->toArray();
        //update
        if (User::where('id', $this->user->id)->update($request->input('password') ? $request->except('_token', 'password_confirmation') : $request->except(['_token', 'password', 'password_confirmation'])))
        {
            //setLog
            $this->setLog('update', json_encode($origin), json_encode($request->except('_token', 'password_confirmation')));
            return ShowMsg('success', getLang('Tips', 'updateSuccess'), '', 1);
        }
        return ShowMsg('error', getLang('Tips', 'updateFail'), '', 1);
    }

    /**
     * 上传头像
     * @param UploadImg $uploadImg
     * @param Request $request
     */
    public function postUpload(UploadImg $uploadImg, Request $request)
    {
        if ($request->hasFile('avatar_file'))
        {
            if ($request->file('avatar_file')->isValid())
            {
                $avatar_file = $request->file('avatar_file');
                $avatar_data = $request->input('avatar_data');
                $avatar_data_obj = json_decode(stripslashes($avatar_data));
                $uploadImg->savePath = config('imgUpdate.memberPath').$request->input('id').'/';
                //横纵比例
                $prefix = md5(time());
                $aspectRatio = [
                    [
                        'width'     =>  $avatar_data_obj->width,
                        'height'    =>  $avatar_data_obj->height,
                        'path'      =>  $prefix.'.png'
                    ]
                ];
                $backData = $uploadImg->upThumb($avatar_file, $avatar_data, $aspectRatio);
                if(count($backData) > 0)
                {
                    $origin = User::where('id', $request->input('id'))->first();
                    //更新数据
                    $check = User::where('id', $request->input('id'))->update(['thumb' => $backData['thumb']]);
                    if($check)
                    {
                        //setLog
                        $this->setLog('updateThumb', json_encode($origin), json_encode($backData));
                        $backData['msg'] = '更新成功';
                    }else{
                        $backData['msg'] = '更新失败';
                    }
                    //返回数据
                    echo json_encode($backData);
                }
            }
        }
    }

    /**
     * 记录日志
     * @param string$type 类型 create update delete
     * @param json null $origin 事件发生前
     * @param json null $ending 事件发生后
     */
    private function setLog($type, $origin = NULL, $ending = NULL)
    {
        switch ($type)
        {
            case 'updateThumb':
                $event = [
                    'msg'   =>  'me.updateThumb',
                    'type'  =>  'Update'
                ];
                break;
            case 'update':
                $event = [
                    'msg'   =>  'me.update',
                    'type'  =>  'Update'
                ];
                break;
        }
        //push to queue
        $geoIP = geoip()->getLocation();
        $this->dispatch(new SetAdminLog($this->user->id, $geoIP, $event['msg'], Carbon::now(), $event['type'], $origin, $ending));
    }
}
